<script lang="ts">
import { computed, ref } from 'vue';

export interface CurrencyIconProps {
  symbol?: string;
  size?: string;
  cdn?: string;
  iconType?: 'img' | 'text';
}

const imgIcons = ref<Record<string, string>>({
  BTC: 'https://api.iconify.design/cryptocurrency-color:0xbtc.svg',
});
const textIcons = ref(['¥', '€', '₱', '$', '৳', '£', '₪', '₹', '₩', '₽', '฿', '₺', '₫', 'R', '₴']);
const fullback = '';

const checkHttpUrl = (value: unknown) => String(value).startsWith('http');
const checkBase64 = (value: unknown) => String(value).startsWith('data:image');
</script>

<script setup lang="ts">
defineOptions({
  inheritAttrs: false,
});
const props = withDefaults(defineProps<CurrencyIconProps>(), {
  size: '1.2em',
  symbol: '',
  iconType: 'img',
});

const { cdn: cdnCtx } = useAppContext() ?? {};
const cdn = computed(() => props.iconType === 'img' ? (props.cdn || toValue(cdnCtx)) : '');
const src = computed(() => {
  if (checkHttpUrl(props.symbol) || checkBase64(props.symbol))
    return props.symbol;
  else if (props.iconType === 'text' || textIcons.value.includes(props.symbol))
    return props.symbol;
  else if (cdn.value)
    return `${cdn.value}/currency/${props.symbol}.svg`;
  else
    return (imgIcons.value[props.symbol.toUpperCase()] ?? fullback);
});

function onError(ev: Event) {
  const $img = ev.target as HTMLImageElement;
  $img.src = fullback;
}
</script>

<template>
  <img
    v-if="checkHttpUrl(src) || checkBase64(src)"
    v-bind="$attrs"
    class="symbol-icon"
    :src="src"
    :alt="props.symbol"
    :style="{ fontSize: $props.size }"
    @error="onError"
  >
  <span v-else v-bind="$attrs" class="symbol-text">{{ src }}</span>
</template>

<style lang="scss" scoped>
img.symbol-icon {
  width: 1em;
  height: 1em;
}
</style>
